package com.lincoln.gateway.zuul;

import com.alibaba.fastjson.JSONObject;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class HttpUtil {
//    public static String redisServer = "193.112.77.149";
    public static String redisServer = "127.0.0.1:8080";

    public static String token = null;
    public static Long token_data = null;
    public static String refresh_token = null;
    public static Long refresh_token_data = null;

    public static String username = "gateway-zuul";
    public static String password = "gateway-zuul";

    public static Map<String, Map<String, ZuulProperties.ZuulRoute>> getSetting() {
        try {
            Map<String, Map<String, ZuulProperties.ZuulRoute>> res = new ConcurrentHashMap<>(1);
            Map<String, List<Setting>> maps = JSONObject.parseObject(readRedis("pool"), Map.class);
            for (String key : maps.keySet()) {
                Map<String, ZuulProperties.ZuulRoute> server = new LinkedHashMap<>();
                for (Setting setting : maps.get(key)) {
                    ZuulProperties.ZuulRoute zuulRoute = new ZuulProperties.ZuulRoute();
                    zuulRoute.setId(setting.getPath());
                    zuulRoute.setPath(setting.getPath());
                    zuulRoute.setUrl(setting.getUrl());
                    zuulRoute.setStripPrefix(setting.getStripPrefix());
                    server.put(setting.getPath(), zuulRoute);
                }
                res.put(key, server);
            }
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            return new ConcurrentHashMap<>(1);
        }
    }


    public static String readRedis(String key) throws Exception {
        URL url = new URL("http://" + redisServer + "/redis/get?key=" + key);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("token", getToken());
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        connection.setUseCaches(false);
        String content = readContent(connection);
        JSONObject jsonObject = JSONObject.parseObject(content);
        return jsonObject.getString("data");
    }

    public static String getToken() throws Exception {
        if (token_data != null && System.currentTimeMillis() >= token_data) {
            token = null;
        }
        if (refresh_token_data != null && System.currentTimeMillis() >= refresh_token_data) {
            refresh_token = null;
        }

        if (refresh_token == null) {
            dispathOauth(username, password);
        }

        if (refresh_token != null && token == null) {
            refresh(refresh_token);
        }
        return token;
    }

    /**
     * 代理请求token
     *
     * @param username
     * @param password
     * @return
     * @throws Exception
     */
    public static void dispathOauth(String username, String password) throws Exception {
        URL url = new URL("http://" + redisServer + "/login?username=" + username + "&password=" + password);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setUseCaches(false);
        readToken(readContent(connection));
    }

    /**
     * 代理请求token
     *
     * @param refreshToken
     * @return
     * @throws Exception
     */
    public static void refresh(String refreshToken) throws Exception {
        URL url = new URL("http://" + redisServer + "/refresh?refreshToken=" + refreshToken);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setUseCaches(false);

        readToken(readContent(connection));
    }

    public static String readContent(HttpURLConnection connection) {
        String content;
        try {
            InputStream inputStream = connection.getInputStream();
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            content = new String(bytes);
            inputStream.close();
            connection.disconnect();
            return content;
        } catch (IOException e) {
            Map<String, String> res = new HashMap<>(1);
            res.put("msg", "权限错误!");
            return "";
        }
    }

    public static void readToken(String content) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(content);
            token = jsonObject.getJSONObject("data").getString("access_token");
            token_data = System.currentTimeMillis() + 900 * 1000;
            refresh_token = jsonObject.getJSONObject("data").getString("refresh_token");
            refresh_token_data = System.currentTimeMillis() + 3600 * 1000;
            return;
        } catch (Exception e) {
            Map<String, String> res = new HashMap<>(1);
            res.put("msg", "权限错误!");
            return;
        }
    }
}
